#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import re
import datetime
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = ['SimHei','Times New Roman']
plt.rcParams['axes.unicode_minus'] = False

# 全局变量
namespace = os.getcwd() + "/hubei/"

# yesterday = str(datetime.date.today() + datetime.timedelta(-1)).replace('-', '')
yesterday = 20220331
dayList = range(int(yesterday), 20220300, -1)

xAxis = [int(str(dt)[-2:]) for dt in dayList if dt]
yAxisA = []
yAxisB = []

def init():
    # 遍历日期 dayList: type is <class 'range'>
    for date in dayList:
        # xAxis.append(str(str(date)[-2:]))
        path = namespace + str(date) + '.txt'
        # print('--> ' + path) # 文件路径
        fr = open(path, 'r', encoding="UTF-8")
        data = fr.read()
        passage = data.split('\n')

        # 解析每天的数据信息 res => tuple
        res = parseDayInfo(int(date), passage)
        yAxisA.append(res[0])
        yAxisB.append(res[-1])
        # exit(0)
    print('len(%d)' % len(xAxis), xAxis)
    print('len(%d)' % len(yAxisA), yAxisA)
    print('len(%d)' % len(yAxisB), yAxisB)
    buildBar()
    pass

def parseDayInfo(date, message):
    a = 0
    b = 0
    for line in message:
        matches = re.findall(r'(\d+月\d+日\d+-\d+时，).*?', line, re.M)
        if matches:
            line = re.sub(r'（.*?）', '', line)
            line = line.rsplit('时，')[1]

            rega = re.findall(r'(无?新增本土.*?例)，', line)
            regb = re.findall(r'(无?境外输入.*?例)，', line)
            lsa = re.findall(r'\d+', '，'.join(rega))
            lsb = re.findall(r'\d+', '，'.join(regb))

            a = sum([int(i) for i in lsa if i])
            b = sum([int(i) for i in lsb if i])

            print("{} --> 新增本土：{}，境外输入：{}".format(date,a,b))
            return a, b
        pass

def buildBar():
    name_list = xAxis
    num_list = yAxisA
    num_list1 = yAxisB
    # 设置标题
    plt.title('湖北省3月份疫情（本土新增和境外输入）状况')
    # plt.figure(figsize=(15, 5), dpi=80)

    # bar(x，height， width，*，align=‘center’，**kwargs)
    bar1List = plt.bar(range(len(num_list)), num_list, label='新增本土',fc = 'y')
    for bar in bar1List:
        a = bar.get_height()
        b = bar.get_x()
        plt.text(b + 0.15, a, str(a), va='bottom')
    bar2List = plt.bar(range(len(num_list)), num_list1, bottom=num_list, label='境外输入',tick_label = name_list,fc = 'r')
    for bar in bar2List:
        y = bar.get_height()
        x = bar.get_x()
        plt.text(x + 0.15, y, str(y), va='bottom')
    plt.legend()
    plt.savefig('./hubei/bar.png')
    plt.show()
    pass

init()